﻿using CommonEntity.CPUEntity;
using CommonEntity.PackageEntity;
using CommonHelper;
using CPUAPI.Context;
using DotNetCore.CAP;
using Microsoft.AspNetCore.Http;
using Microsoft.AspNetCore.Mvc;
using Microsoft.EntityFrameworkCore;
using Microsoft.Extensions.Configuration;
using Microsoft.Extensions.Logging;
using Newtonsoft.Json;
using StackExchange.Redis;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;

namespace CPUAPI.Controllers
{
    /// <summary>
    /// CPU相关信息服务接口
    /// </summary>
    [Route("[controller]")]
    [ApiController]
    public class CPUController : ControllerBase
    {
        private readonly ILogger<CPUController> _logger;
        private readonly IConfiguration _configuration;
        private readonly ICapPublisher _capBus;
        private readonly CPUContext _context;
        private readonly IDatabase _redis;

        public CPUController(ILogger<CPUController> logger, IConfiguration configuration, ICapPublisher capPublisher, CPUContext context, RedisHelper client)
        {
            _logger = logger;
            _configuration = configuration;
            _capBus = capPublisher;
            _context = context;
            _redis = client.GetDatabase();
        }

        /// <summary>
        /// 获取CPU服务IP和端口
        /// </summary>
        /// <returns></returns>
        [Route("CpuServer")]
        [HttpGet]
        public IActionResult GetCpuServer()
        {
            return Ok($"【CPU服务】{DateTime.Now.ToString("yyyy-MM-dd HH:mm:ss")}--{Request.HttpContext.Connection.LocalIpAddress}:{_configuration["ConsulSetting:ServicePort"]}");
        }

        /// <summary>
        /// 获取CPU剩余数量
        /// </summary>
        /// <param name="ID">ID</param>
        /// <returns></returns>
        [Route("CpuCount")]
        [HttpGet]
        public async Task<IActionResult> GetCpuCountByID(int ID)
        {
            try
            {
                var curCount = await _context.CPUInfos.Where(q => q.ID == ID).Select(a => a.TotalCount).FirstOrDefaultAsync();
                return Ok(curCount);
            }
            catch (Exception ex)
            {
                return BadRequest(ex);
            }            
        }

        /// <summary>
        /// 创建更新CPU
        /// </summary>
        /// <param name="cpu">CPU信息</param>
        /// <returns></returns>
        [Route("CreateUpdate")]
        [HttpPost]
        public async Task<IActionResult> CreateUpdateCPU(CPUInfo cpu)
        {
            try
            {
                using (var trans = _context.Database.BeginTransaction(_capBus, autoCommit: true))
                {
                    var curCPU = _context.CPUInfos.FirstOrDefault(cpuinfo => cpuinfo.Name == cpu.Name);
                    if (curCPU == null)
                    {
                        cpu.LastProduceTime = DateTime.Now;
                        cpu.TotalCount = 1;
                        _context.CPUInfos.Add(cpu);
                    }
                    else
                    {
                        curCPU.LastProduceTime = DateTime.Now;
                        curCPU.TotalCount += 1;
                    }
                    var r = await _context.SaveChangesAsync() > 0;
                    if (r)
                    {
                        //更新redis
                        var batchExe = _redis.CreateBatch();
                        _redis.KeyDelete("CPUInfos");
                        _context.CPUInfos.ToList().ForEach(a => batchExe.SetAddAsync("CPUInfos", JsonConvert.SerializeObject(a)));
                        batchExe.Execute();

                        return Ok();
                    }
                    return BadRequest();
                }
            }
            catch (Exception ex)
            {
                return BadRequest(ex);
            }
        }

        /// <summary>
        /// 组装手机 订阅CPU减少事件
        /// </summary>
        /// <param name="message"></param>
        /// <returns></returns>
        [NonAction]
        [CapSubscribe("PackageAPI.CreatePhone")]
        public async Task ReduceCPU(PackageInfo message)
        {
            //业务代码
            var cpuInfo = await _context.CPUInfos.FirstOrDefaultAsync(p => p.ID == message.CPUID);
            cpuInfo.LastProduceTime = DateTime.Now;
            cpuInfo.TotalCount -= 1;

            await _context.SaveChangesAsync();

            //更新redis
            var batchExe = _redis.CreateBatch();
            _redis.KeyDelete("CPUInfos");
            _context.CPUInfos.ToList().ForEach(a => batchExe.SetAddAsync("CPUInfos", JsonConvert.SerializeObject(a)));
            batchExe.Execute();

        }

    }
}
